/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.doeis.minaserver.packet;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author tianbx
 * @date 2015年6月15日
 * @version 1.0
 * 报文编码器，在数据包发送前，先由本对象对报文进行适合网络传输的对象
 */
public final class NettyMessageEncoder extends
	MessageToByteEncoder<Object> {

	  protected static final int maxDataLength = 500 * 1024;//以前默认的是200 * 1024 ，后来由于发送信息比较多进行扩展10倍
	// 字符集
	private final Charset charset = Charset.forName("UTF-8");
		
	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out)
			throws Exception {
		
		Packet packet  = (Packet) msg;
		// 返回包括来去信息的json字符串
		String content = packet.getBody();
		int packetLength = packet.getLength();
		if (packetLength < 0 || packetLength > maxDataLength) {
			throw new Exception("编码时,数据包长度超出协议充许的范围:0<x<"+ maxDataLength+", x=" + packetLength+"\nPacket:"+packet);
		}
		
		out.writeInt( packetLength);
		out.writeByte((byte) packet.getPacketType().ordinal());
		out.writeByte((byte) packet.getVersion().ordinal());
		out.writeByte((byte) packet.getDirection().ordinal());
		out.writeByte(packet.getCmd());
		out.writeInt(packet.getNotifyType());
		out.writeByte((byte) packet.getTransType().ordinal());
		out.writeLong(packet.getTime());
		
		out.writeByte(packet.getFromLen());
		out.writeByte(packet.getToLen());
		out.writeByte(packet.getPwdLen());
		
		out.writeBytes(packet.getFrom().getBytes(charset));
		out.writeBytes(packet.getTo().getBytes(charset));
		out.writeBytes(packet.getPwd().getBytes(charset));
		
		out.writeBytes(content.getBytes(charset));
	}

 
}
